<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100"/>
      <el-table-column label="品名" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.name`" :rules="formRules.name" class="mb-0px!">
            <el-input v-model="row.name" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="型号规格" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.model`" :rules="formRules.model" class="mb-0px!">
            <el-input v-model="row.model" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unit`" :rules="formRules.unit" class="mb-0px!">
            <el-input v-model="row.unit" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.quantity`" :rules="formRules.quantity" class="mb-0px!">
            <el-input @change="calcTotal(row)"  v-model="row.quantity" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unitPrice`" :rules="formRules.unitPrice" class="mb-0px!">
            <el-input  @change="calcTotal(row)" v-model="row.unitPrice" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.amount`" :rules="formRules.amount" class="mb-0px!">
            <el-input disabled v-model="row.amount" placeholder="" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加</el-button>
    <el-button @click="handleImport" round>+ 导入</el-button>
  </el-row>
  <el-dialog v-model="dialogFormVisible" title="导入" width="1000">
    <div style="width:100%;height:500px;overflow-y:auto;overflow-x: hidden">
      <content-dict @selectConfirm="selectConfirm" :dialog="true"/>
    </div>
<!--    <template #footer>-->
<!--      <div class="dialog-footer">-->
<!--        <el-button @click="dialogFormVisible = false">Cancel</el-button>-->
<!--        <el-button type="primary" @click="dialogFormVisible = false">-->
<!--          Confirm-->
<!--        </el-button>-->
<!--      </div>-->
<!--    </template>-->
  </el-dialog>
</template>
<script setup lang="ts">
import contentDict from '@/views/biz/invoiceDict/index.vue'
import * as UserApi from "@/api/system/user";
import {BizInvoiceManagementApi} from "@/api/biz/invoice";

const props = defineProps<{
  invoiceId: number, // 学生编号（主表的关联字段）
  teamMsg: any[] // 学生编号（主表的关联字段）
}>()
const formLoading = ref(false) // 表单的加载中
const dialogFormVisible = ref(false)
const handleImport = () => {
  dialogFormVisible.value = true
}
const formData = ref<any[]>([])
const formRules = reactive({
  // studentId: [{ required: true, message: '学生编号不能为空', trigger: 'blur' }],
  // userId: [{required: true, message: '名字不能为空', trigger: 'blur'}],
  // score: [{ required: true, message: '分数不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const selectConfirm = ( list: any[]) => {
  // console.info(list)
  formData.value = [...formData.value, ...list]
  dialogFormVisible.value = false
  // startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

const calcTotal= (row) => {
  if (row.quantity && row.unitPrice ) {
    row.amount = parseFloat(row.quantity) * parseFloat(row.unitPrice)
  }
}
/** 监听主表的关联字段的变化，加载对应的子表数据 */

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.invoiceId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      formData.value = await BizInvoiceManagementApi.getInvoiceItemList(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)


/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    name: undefined,
    model: undefined,
    unit: undefined,
    quantity: undefined,
    unitPrice: undefined,
    amount: undefined,
  }
  row.invoiceId = props.invoiceId as any
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

const setDeptName = (row, userId) => {
  row.deptName = userList.value.find(item => item.id === userId).deptName
}

defineExpose({validate, getData})
</script>
